<template>
  <div id="mainportal" class="container" style="background-color: #fff;">

  <comhead title="VIN查询" isLeftIcon="true" leftIconName="angle-left" @leftClick="foBack()" isRightIcon="true" rightIconName="ellipsis-h" @rightClick="updataActive()"></comhead>
   


    <input type="file" ref="logo" style="display:none;" @change="isSizeClear();" accept="image/*"/>


<div  style='padding-top:22px;width:100%;height:100vh; border-top: 1px solid #e5e5e5;'>
<div style='display:flex;align-items:center;background-color:#fff;border: 1px solid #e5e5e5; border-radius: 5px;margin:0 20px 20px 20px '>
     <div style='padding:5px 10px;display: flex;justify-content: center;align-items: center;' @click='$refs.logo.click()'>
     
       <img src='../../image/xiangji.png' style='width:30px;height:30px;' />

     </div>
        <input style='flex:1;padding-right: 10px;font-size:14px;' placeholder='输入17位车架号智能匹配' maxlength="17" v-model="vin" />
        <div class='next' @click='goCategory()' :style="'background-color:'+$store.getters.getMerchant.themeColors">
          <img src='../../image/4.png' style='width:20px;height:20px;'/>
        </div>
      </div>

<div style="display:flex;    align-items: center;">
  <img  alt="" v-for="(item,index) in showImage" :src="item" style="    width: 100px;margin: 10px;"    @click="getImg(showImage)" >
</div>


        <div style='font-size:14px;padding:0 0 10px 20px;  border-bottom: solid #e5e5e5 1px;' v-if="vinStoryList.length>0">
        历史记录
        </div>

 <!-- data-modelid='{{item.model_id}}' -->
  <div class='car_item' v-for="(item,index) in vinStoryList" @click='setModelId(item.model_id,item.pic ,item)'>
     
      <img :src='item.pic' style='width:70px;margin:10px 15px 10px 0;' />
        <div style='flex:1;'>
          <div>{{item.brand}}  {{item.model}}</div>
          <div :style="'color:'+$store.getters.getMerchant.themeColors">查询成功</div>
          <div class='inconsequential'>{{item.vin}}</div>
        </div>
        <div>
             <!-- data-index='{{index}}' -->
     <img src='../../image/50.png' @click.stop='delStoryItem(index)' class='delStoryCar' style='width:12px; height:12px;'/>
        <div>　</div>
        <div class='inconsequential' style='margin-right:5px;' >{{item.queryTime}}</div>
        </div>
  </div>



</div>




<div  v-if="queryModel" style=' display: flex;align-items:center;justify-content: center;position: fixed;bottom: 0; z-index: 999;background-color: rgba(0, 0, 0, 0.498039);height: 100%;width: 100%;'>


  <div class='centerContent'>

    <div style='color:#999999;padding:10px 0; text-align:center;border: solid 1px #e5e5e5; border-top-left-radius: 8px;  border-top-right-radius: 8px;'>
      <span>{{returnMessage}}</span>
    </div>
    <div :style="returnList.length>5?'height:50vh':''">
      <div  style="height:100%">
<!-- data-modelid='{{item.model_id}}' data-index='{{index}}' -->
        <div v-for="(item,index) in returnList"  class='winfloat item-content' @click='setModelIdlinkVinFilter(item.model_id,index,item.pic)' >
          <img :src='item.pic' style="width:50px;height:40px;margin:0 10px;"/>
          <div style='flex:1; overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-size:14px; '>
            <div>{{item.brand}} {{item.series}}</div>
            <div style=''>{{item.model}}</div>
          </div>
          <img src='../../image/back.png' style="width:20px;height:20px;margin:8px;"/>
        </div>
      </div>
    </div>
    <div class='item-content close1' :style="'color:'+$store.getters.getMerchant.themeColors" @click='close'>
      <span>关闭</span>
    </div>
  </div>
</div>











  </div>
</template>

 
 

<script>
import { Toast, Swipe, SwipeItem, Switch, MessageBox } from "mint-ui";
import { Indicator } from "mint-ui";
import { Tabbar, TabItem } from "mint-ui";
import { TabContainer, TabContainerItem } from "mint-ui";
import comhead from "../../common/coffee/Comhead";

export default {
  data() {
    return {
      queryModel: false,
      returnList: [],
      vinStoryList: [],
      vin: "",
      vinPage: true,
      icon:'',
      showImage:[],
      li_module: false
    };
  },
  computed: {},

  methods: {
        getImg(imgurl){
  WeixinJSBridge.invoke("imagePreview",{
    "urls":imgurl
  })
},
    isSizeClear() {
      Indicator.open({
        text: "上传中...",
        spinnerType: "fading-circle"
      });
      const self = this;
      let form = new FormData();
      let logo = this.$refs.logo.files;
      form.append("file", logo[0]);

      let url = this.$baseUrl.bizUrl + "/fileupload";

      let callBack = res => {
        Indicator.close();

        if (res == null) {
          console.log("网络请求错误1！");
          return;
        }

        if (res.data.status != 200) {
          MessageBox.alert(res.data.message);
          return;
        }
        if (res.data.status == 200) {

          this.showImage=[res.data.data.filename]
          this.imageToText(res.data.data.filename);
        }
      };
      this.$reqFormUpload(url, form, callBack);
    },
    imageToText(pic) {
      let self = this;
      let url = this.$baseUrl.bizUrl + "/vinpic/qurey";
      let data = {
        token: this.$store.getters.getLoginStatus.token,
        userId: this.$store.getters.getLoginStatus.userId,
        pic: pic
      };

      let callBack = res => {
        if (res == null) {
          console.log("网络请求错误！");
          return;
        }
        if (res.data.status != 200) {
          console.log("请求数据错误");
          return;
        }
        if (res.data.data.length > 0) {
            this.vin= res.data.data[0]
        } else {
            this.returnMessage= "扫描图片未得到相应信息"
             this.queryModel= !this.queryModel
        }
      };
      this.$reqFormPost(url, data, callBack);
    },
    delStoryItem(index) {
      let self = this;
      this.removeByValue(this.vinStoryList, this.vinStoryList[index]);
      let storage = window.localStorage;
      storage.StoryItem = JSON.stringify(this.vinStoryList);
      this.queryVinStory();
    },
    // 列表点击设置车型并且跳转
    setModelId(e,pic, element) {
    	
    	this.vinStoryList.forEach((item, index) => {
    		if(item.model_id == e) {
    			
    			this.vinStoryList.splice(index,1)
    		}
    	})
    	element.createTime = new Date()
    	this.vinStoryList.unshift(element)
    	let storage = window.localStorage;
      storage.StoryItem = JSON.stringify(this.vinStoryList);
    	this.icon = pic
    	this.queryVinStory()
      this.setModelIdByVin(e);

      
    },
    // 设置车型并且插入历史跳转
    setModelIdlinkVinFilter(modelid, index,pic) {
      console.log(modelid);
      this.icon = pic
      if (modelid) {
        let modelVin = this.vinStoryList;

        let a = {
          createTime: new Date(),
          vin: this.vin,
          brand: this.returnList[index].brand,
          model: this.returnList[index].model,
          model_id: this.returnList[index].model_id,
          pic: this.returnList[index].pic
        };

        modelVin.forEach((model, modelIndex) => {
          if (model.model_id == a.model_id) {
            this.removeByValue(modelVin, model);
          }
        });

        if (modelVin.length > 30) {
          this.removeByValue(modelVin, modelVin[modelVin.length - 1]);
        }
        modelVin.unshift(a);

        let storage = window.localStorage;
        storage.StoryItem = JSON.stringify(modelVin);

        this.setModelIdByVin(modelid);
      }
    },
    goCategory() {
      if (this.vin === "" || this.vin.length < 17) {
        this.returnMessage = "请输入17位车架号";
        this.queryModel = !this.queryModel;
        return;
      }

      this.returnList = [];

      let self = this;
      let url = this.$baseUrl.bizUrl + "/vin/qurey";
      let data = {
        merchantId: this.$store.getters.getMerchant.merchantId,
        vin: this.vin
      };
      //发起网络请求
      let callBack = res => {
        if (res == null) {
          console.log("网络请求错误！");
          return;
        }
        if (res.data.status != 200) {
          this.returnMessage = res.data.message;
          this.queryModel = !this.queryModel;
          return;
        }

        if (res.data.status === 200) {
          console.log("查询vin", res.data.data);

          if (res.data.data.length === 0) {
            this.returnMessage = "未查询到相应信息";
            this.queryModel = !this.queryModel;
          } else if (res.data.data.length === 1) {
            let modelVin = this.vinStoryList;

            let a = {
              createTime: new Date(),
              vin: this.vin,
              brand: res.data.data[0].brand,
              model: res.data.data[0].model,
              model_id: res.data.data[0].model_id,
              pic: res.data.data[0].pic
            };
            if(res.data.data && res.data.data[0].pic){
            	this.icon = res.data.data[0].pic
            }
            
            modelVin.forEach((model, modelIndex) => {
              if (model.model_id == a.model_id) {
                this.removeByValue(modelVin, model);
              }
            });
            if (modelVin.length > 30) {
              this.removeByValue(modelVin, modelVin[modelVin.length - 1]);
            }
            modelVin.unshift(a);

            let storage = window.localStorage;
            storage.StoryItem = JSON.stringify(modelVin);

            this.setModelIdByVin(res.data.data[0].model_id);
          } else if (res.data.data.length > 1) {
            (this.returnMessage = "匹配到以下结果，请选择查看"),
              (this.returnList = res.data.data),
              (this.queryModel = !this.queryModel);
          }
        }
      };
      this.$reqFormPost(url, data, callBack);
    },

    setModelIdByVin(model_id) {
      let stroge = window.localStorage;
      stroge.carId = model_id;
      if(window.localStorage.getItem('linklist')) {
				window.localStorage.removeItem('linklist')
			}
      this.$router.push({
					name: "order-result"
				});
      //this.li_module ? this.goPage(model_id):this.$router.push({ name: "category" });
    },
    goPage(model_id){
    	 	let url = this.$baseUrl.sizUrl+ '/merchant/catlist'
    	 	let data = {
	      	merchantId: this.$store.getters.getMerchant.merchantId,
	      	modelId: model_id
	    	}
    	 	let self = this
    	 		let callBack = (res) => {
			      console.log(res)
			      if (res == null) {
			        console.log("网络请求错误！");
			        return;
			      }
			      if (res.status != 200) {
			        console.log("请求数据错误");
			        return;
			      }
			      if (res.status === 200) {
			        let selfs = self
			        console.log(selfs)
			        // 当前只有一个分类且当前只有一个商品
			        console.log(res.data.data.goodsCount[res.data.data.children[0].catId])
			        console.log(res.data.data.children.length)
			        if (res.data.data.children.length == 1 && res.data.data.goodsCount[res.data.data.children[0].catId] === 1) {
			          // 请求获取商品id
			          
			          let goodsUrl = selfs.$baseUrl.bizUrl + '/goods/front/list'
			
			          let datas = {
			            merchantId: selfs.$store.getters.getMerchant.merchantId,
			            userId: selfs.$store.getters.getLoginStatus.userId ? selfs.$store.getters.getLoginStatus.userId: '',
			            firstCatId: res.data.data.children[0].parentId,
			            secCatIds: res.data.data.children[0].catId,//二级分类id
			            carId: model_id
			          }
			
			          let callBacks = (result) => {
			            let targetSelf = selfs
			            console.log(targetSelf)
			            if (result == null) {
			              console.log("网络请求错误！");
			              return;
			            }
			            if (result.status != 200) {
			              console.log("请求数据错误");
			              return;
			            }
			            console.log(result.data.data.length)
			            if (result.data.data.length > 0) {

											console.log(result.data.data[0].goodsId,model_id,targetSelf.vinPage,targetSelf.icon)
											targetSelf.$router.push(
					              "/productdetail?id=" +
					                result.data.data[0].goodsId  +
					                "&carId=" +
					                model_id+
					                "&icon="+
					                targetSelf.icon+
					                "&vinPage="+targetSelf.vinPage
					                
					            );
			
			            }
			          }
			          selfs.$reqFormPost(goodsUrl, datas, callBacks)
			        } else {
			         
			          selfs.$router.push({ name: "category" })
			         
			        }
		      }
		    }
    	  this.$reqFormPost(url, data, callBack)    
    	 
    },

    close() {
      this.queryModel = !this.queryModel;
    },
    removeByValue(arr, val) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
          arr.splice(i, 1);
          break;
        }
      }
    },
    getDateDiff(dateTimeStamp) {
      var result;
      var minute = 1000 * 60;
      var hour = minute * 60;
      var day = hour * 24;
      var halfamonth = day * 15;
      var month = day * 30;
      var now = new Date().getTime();
      var diffValue = now - dateTimeStamp;
      if (diffValue < 0) {
        return;
      }
      var monthC = diffValue / month;
      var weekC = diffValue / (7 * day);
      var dayC = diffValue / day;
      var hourC = diffValue / hour;
      var minC = diffValue / minute;
      if (monthC >= 1) {
        if (monthC <= 12) result = "" + parseInt(monthC) + "月前";
        else {
          result = "" + parseInt(monthC / 12) + "年前";
        }
      } else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
      } else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
      } else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
      } else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
      } else {
        result = "刚刚";
      }

      return result;
    },
    queryVinStory() {
      let self = this;
      let storage = window.localStorage;

      console.log(storage.StoryItem)
      let StoryItem =storage.StoryItem? JSON.parse(storage.StoryItem):[];

      StoryItem.forEach((item, index) => {
        Object.assign(item, {
          queryTime: self.getDateDiff(new Date(item.createTime).getTime())
        });
      });

      this.vinStoryList = StoryItem;
    },
    goSign() {
      this.$router.push({ name: "sign" });
    },
    foBack() {
      this.$router.go(-1);
    }
  },
  mounted() {
    document.title = 'VIN查询'
    this.queryVinStory();
    if(this.$store.getters.getMerchant.merchantId == 'Mer5af261c3db573c5063f0fdf4' || this.$store.getters.getMerchant.merchantId == 'Mer5b10b6cedb573c72d45b5c03') {
			this.li_module = true
		}
  },
  components: {
    Tabbar,
    TabItem,
    TabContainer,
    TabContainerItem,
    comhead,
    Swipe,
    SwipeItem
  }
};
</script>
<style>
input-placeholder {
  font-size: 14px;
}
.next {
  font-size: 14px;
  color: #fff;
  padding: 10px 15px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  /* border-radius:0; */
}

/* example/query/query.wxss */
.winfloat {
  padding: 10px 0;
  display: flex;
  border-bottom: solid 1px #e5e5e5;
  align-items: center;
  font-size: 12px;
}
.close1 {
  padding: 10px 0;
  text-align: center;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}
.item-content:active {
  background-color: #f7f7f7;
}

.centerContent {
  background-color: #fff;
  border-radius: 8px;
  width: 70%;
  font-size: 14px;
}
.bankMessage {
  position: relative;
  top: -24rpx;
  background: #f3f3f3;
  width: 3em;
}

.car_item {
  height: 100px;
  position: relative;
  border-bottom: solid #e5e5e5 1px;
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: space-between;
  margin-left: 20px;
}
.inconsequential {
  font-size: 24rpx;
  color: #999;
}
.delStoryCar {
  position: absolute;
  right: 10px;
  top: 10px;
  padding: 5px;
}
</style>



<!-- Add "scoped" attribute to limit CSS to this component only -->
